package cn.dakaqi.web.web.pingan;

import cn.dakaqi.api.qnzyz.util.BHAccesssToken;
import cn.dakaqi.entities.PinganOpen;
import cn.dakaqi.entities.PinganVoucherCenter;
import cn.dakaqi.entities.Volunteer;
import cn.dakaqi.entities.VolunteerInsurance;
import cn.dakaqi.member.service.VolunteerService;
import cn.dakaqi.pingan.services.PinganInsuranceService;
import cn.dakaqi.pingan.services.PinganOpenService;
import cn.dakaqi.pingan.services.PinganVoucherCenterService;
import cn.dakaqi.utils.DateUtil;
import cn.dakaqi.utils.JsonResult;
import cn.dakaqi.volunteer.insurance.services.VolunteerInsuranceService;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import org.springside.modules.web.MediaTypes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;

/**
 * Created by chunyang on 2016/6/16.
 */
@Controller
@RequestMapping(value = "/pa")
@Slf4j
public class PAController
{
    @Autowired
    VolunteerService volunteerService;
    @Resource
    private PinganOpenService pinganOpenService;
    @Autowired
    private PinganInsuranceService pinganInsuranceService;
    @Autowired
    BHAccesssToken bhAccesssToken;
    @Resource
    private VolunteerInsuranceService volunteerInsuranceService;
    @Autowired
    private PinganVoucherCenterService pinganVoucherCenterService;

    /**
     * 保险购买首页说明页面
     * @param platform
     * @param volunteerCode
     * @return
     */
    @RequestMapping(method = RequestMethod.GET)
    public ModelAndView index(@RequestParam(value = "platform", defaultValue = "U") String platform,@RequestParam(value = "volunteerCode") String volunteerCode)
    {
        if(StringUtils.isBlank(volunteerCode))
        {
            String view = "pingan/unapply";
            ModelAndView modelAndView = new ModelAndView(view);
            modelAndView.addObject("message", "请先加入一上社团,成为注册志愿者");
            return modelAndView;
        }

        Volunteer volunteer = this.volunteerService.findByVolunteerCode(volunteerCode);
        if(null == volunteer)
        {
            String view = "pingan/unapply";
            ModelAndView modelAndView = new ModelAndView(view);
            modelAndView = new ModelAndView(view);
            modelAndView.addObject("message", "请先完成登录");
            return modelAndView;
        }

        //检查当前用户是否已购买过保险
        VolunteerInsurance insurance = this.volunteerInsuranceService.findByVolunteerCode(volunteer.getVolunteerCode());
        //检查用户是否已开过平安银行卡号
        PinganOpen pinganOpen = this.pinganOpenService.findByVolunteerCode(volunteer.getVolunteerCode());
        if(null != pinganOpen && StringUtils.isNotBlank(pinganOpen.getCardNum()) && pinganOpen.getStatus() == PinganOpen.STATUS_YES)
        {
            String view = "pingan/finish";
            ModelAndView modelAndView = new ModelAndView(view);
            modelAndView.addObject("volunteer", volunteer);
            modelAndView.addObject("insurance", insurance);
            modelAndView.addObject("cardNum", pinganOpen.getCardNum());
            return modelAndView;
        }
        if(null != insurance)
        {
            String view = "pingan/insurance";
            ModelAndView modelAndView = new ModelAndView(view);
            modelAndView.addObject("volunteer", volunteer);
            modelAndView.addObject("insurance", insurance);
            modelAndView.addObject("platform", platform);
            modelAndView.addObject("volunteerCode", volunteerCode);
            modelAndView.addObject("memberCode", volunteer.getMemberCode());
            return modelAndView;
        }
        String view = "pingan/index";
        ModelAndView modelAndView = new ModelAndView(view);
        modelAndView.addObject("platform", platform);
        modelAndView.addObject("volunteerCode", volunteerCode);
        modelAndView.addObject("memberCode", volunteer.getMemberCode());

        return modelAndView;
    }

    /**
     * 填写购买者的信息
     * @param platform
     * @param memberCode
     * @return
     */
    @RequestMapping(value = "/toRegPage", method = RequestMethod.GET)
    public ModelAndView toRegPage(@RequestParam(value = "platform", defaultValue = "") String platform, @RequestParam(value = "volunteerCode",required = true) String volunteerCode,@RequestParam(value = "memberCode",required = true) String memberCode)
    {
        Volunteer volunteer = this.volunteerService.findByMemberCode(memberCode);
        //检查当前用户是否已购买过保险
        VolunteerInsurance insurance = this.volunteerInsuranceService.findByVolunteerCode(volunteer.getVolunteerCode());
        if(null != insurance)
        {
            String view = "pingan/insurance";
            ModelAndView modelAndView = new ModelAndView(view);
            modelAndView.addObject("volunteer", volunteer);
            modelAndView.addObject("insurance", insurance);
            modelAndView.addObject("platform", platform);
            modelAndView.addObject("volunteerCode", volunteerCode);
            modelAndView.addObject("memberCode", memberCode);
            return modelAndView;
        }
        //检查用户是否已开过平安银行卡号
        PinganOpen pinganOpen = this.pinganOpenService.findByVolunteerCode(volunteer.getVolunteerCode());
        if(null != pinganOpen && StringUtils.isNotBlank(pinganOpen.getCardNum()) && pinganOpen.getStatus() == PinganOpen.STATUS_YES)
        {
            String view = "pingan/finish";
            ModelAndView modelAndView = new ModelAndView(view);
            modelAndView.addObject("volunteer", volunteer);
            modelAndView.addObject("insurance", insurance);
            modelAndView.addObject("cardNum", pinganOpen.getCardNum());
            return modelAndView;
        }
        //志愿者不存在或不是身份证用户转入无法领取页面
        if (null == volunteer || !volunteer.getCardType().equals("CID") || StringUtils.isBlank(volunteer.getCardNO()))
        {
            String view = "pingan/unapply";
            ModelAndView modelAndView = new ModelAndView(view);
            modelAndView.addObject("message", "目前只支持身份证购买,请完善个人信息");
            return modelAndView;
        }

        //检查当前用户的年龄
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        try
        {
            int age = DateUtil.getAgeByBirthday(sdf.parse(DateUtil.getBirthFromCardNO(volunteer.getCardNO())));
            //若是小7大于70岁的转入无法领取页面
            if(age<7 || age>70)
            {
                String view = "pingan/unapply";
                ModelAndView modelAndView = new ModelAndView(view);
                modelAndView.addObject("message", "您的年龄不满足领取条件");
                return modelAndView;
            }
            else
            {
                String view = "pingan/reg";
                ModelAndView modelAndView = new ModelAndView(view);
                modelAndView.addObject("platform", platform);
                modelAndView.addObject("volunteerCode", volunteerCode);
                modelAndView.addObject("memberCode", memberCode);
                modelAndView.addObject("realName", volunteer.getRealName());
                modelAndView.addObject("cardNO", volunteer.getCardNO());
                modelAndView.addObject("mobile", volunteer.getMobile());
                modelAndView.addObject("age", age);
                //若是在7-17岁间，转入填写监护人页面
                if(age>=7 && age <17)
                    modelAndView.addObject("type", "N");
                else
                    modelAndView.addObject("type", "Y");
                //若是17-70 转入正确页面
                return modelAndView;

            }
        } catch (ParseException e)
        {
            e.printStackTrace();
            String view = "pingan/unapply";
            ModelAndView modelAndView = new ModelAndView(view);
            modelAndView.addObject("message", "无效领取");
            return modelAndView;
        }
    }

    /**
     * 购买保险
     * @param jsonParam
     * @return
     */
    @RequestMapping(value = "/create", method = RequestMethod.POST,produces = MediaTypes.JSON_UTF_8)
    public ResponseEntity<JsonResult> create(@RequestBody String jsonParam)
    {
        PinganOpen param = JSON.toJavaObject(JSON.parseObject(jsonParam),PinganOpen.class);
        JsonResult jsonResult = this.pinganInsuranceService.createInsurance(param);
        return new ResponseEntity<JsonResult>(jsonResult, HttpStatus.OK);
    }

    /**
     * 保险成功购买后的展示页面
     * @param volunteerCode
     * @return
     */
    @RequestMapping(value = "/insurance/{volunteerCode}", method = RequestMethod.GET)
    public ModelAndView insurance(@PathVariable("volunteerCode") String volunteerCode)
    {
        String view = "pingan/insurance";
        Volunteer volunteer = this.volunteerService.findByVolunteerCode(volunteerCode);
        VolunteerInsurance insurance = this.volunteerInsuranceService.findByVolunteerCode(volunteerCode);
        ModelAndView modelAndView = new ModelAndView(view);
        modelAndView.addObject("volunteer", volunteer);
        modelAndView.addObject("insurance", insurance);
        return modelAndView;
    }
    /**
     * 平安银行开户、激活方法
     * @param volunteerCode
     * @param response
     * @return
     */
    @RequestMapping(value = "/activityPingan/{volunteerCode}", method = RequestMethod.GET)
    public ResponseEntity<JsonResult> activityPingan(@PathVariable("volunteerCode") String volunteerCode,HttpServletResponse response,HttpServletRequest request)
    {
        JsonResult jsonResult =  pinganInsuranceService.activityPingan(volunteerCode);
        try
        {
            if(jsonResult.getCode() == JsonResult.CODE_SUCCESS)
                response.sendRedirect(jsonResult.getMessage());
            else if(jsonResult.getCode() == 2)
            {
                String param = jsonResult.getMessage();
                String url = request.getContextPath()+"/pa/finish2?param=" + param;
                response.sendRedirect(url);
            }
        } catch (IOException e)
        {
            e.printStackTrace();
        }
        return new ResponseEntity<JsonResult>(jsonResult, HttpStatus.OK);
    }

    /**
     * 平安账号成功鉴权后，回调地址
     * @param param
     * @return
     */
    @RequestMapping(value = "/finish", method = RequestMethod.GET)
    public ModelAndView finish(@RequestParam(value = "param", required = true) String param)
    {
        String view = "pingan/finish";

        String[] params = param.split(";");
        String volunteerCode = params[0];
        String cardNum = params[1];
        PinganVoucherCenter pinganVoucherCenter = new PinganVoucherCenter(cardNum);
        this.pinganVoucherCenterService.save(pinganVoucherCenter);
        Volunteer volunteer = this.volunteerService.findByVolunteerCode(volunteerCode);
        VolunteerInsurance insurance = this.volunteerInsuranceService.findByVolunteerCode(volunteerCode);
        ModelAndView modelAndView = new ModelAndView(view);
        modelAndView.addObject("volunteer", volunteer);
        modelAndView.addObject("insurance", insurance);
        modelAndView.addObject("cardNum", cardNum);
        return modelAndView;

    }

    /**
     * 平安账号成功鉴权后，回调地址
     * @param param
     * @return
     */
    @RequestMapping(value = "/finish2", method = RequestMethod.GET)
    public ModelAndView finish2(@RequestParam(value = "param", required = true) String param)
    {
        String view = "pingan/finish";

        String[] params = param.split(";");
        String volunteerCode = params[0];
        String cardNum = params[1];
        Volunteer volunteer = this.volunteerService.findByVolunteerCode(volunteerCode);
        VolunteerInsurance insurance = this.volunteerInsuranceService.findByVolunteerCode(volunteerCode);
        ModelAndView modelAndView = new ModelAndView(view);
        modelAndView.addObject("volunteer", volunteer);
        modelAndView.addObject("insurance", insurance);
        modelAndView.addObject("cardNum", cardNum);
        return modelAndView;

    }

}
